package com.bee.auth.client;

import java.util.List;
import java.util.Map;

/**
 * @author Damin.yang
 * @date 2019/08/15 18:29
 */
public class AuthHolder {

    public static final String USER_ID = "id";
    public static final String NAME = "name";
    public static final String USERNAME = "username";
    public static final String PHONE = "phone";
    public static final String TYPE = "type";
    public static final String ORG_ID = "orgId";
    public static final String TOKEN = "token";
    public static final String ROLES = "roles";

    private static final ThreadLocal<Map<String, Object>> THREADLOCAL = new ThreadLocal<>();

    public static void set(Map<String, Object> map){
        THREADLOCAL.set(map);
    }

    public static Map<String, Object> get(){
        return THREADLOCAL.get();
    }

    public static Long getUserId() {
        return Long.valueOf(get(USER_ID).toString());
    }

    public static Long getOrgId() {
        Object orgId = get(ORG_ID);
        if (orgId == null) {
            return null;
        }
        return Long.valueOf(orgId.toString());
    }

    public static String getUser() {
        Long userId = getUserId();
        return userId == null ? null : String.valueOf(userId);
    }

    public static String getName() {
        return (String) get(NAME);
    }

    public static String getUsername() {
        return (String) get(USERNAME);
    }

    public static String getPhone() {
        return (String) get(PHONE);
    }

    /**
     * 0：普通用户，1：内部用户
     * @return
     */
    public static Integer getType() {
        return (Integer) get(TYPE);
    }

    public static String getToken() {
        return (String) get(TOKEN);
    }

    private static Object get(String key) {
        Map<String, Object> map = get();
        if (map == null) {
            return null;
        }
        return map.get(key);
    }

    public static List<String> getRoles() {
        return (List<String>) THREADLOCAL.get().get(ROLES);
    }

    public static void remove() {THREADLOCAL.remove();}
}
